package com.lovo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserBean;
import com.lovo.bean.UserCommentBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResultCode;
import com.lovo.service.IUserCommentService;
import com.lovo.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@RequestMapping("users")
public class UserController {
    @Resource
    IUserService service;


    @RequestMapping("/login")
    @ResponseBody
    public Object login(String userName, String password) throws GlobalHandleException {

        // 把用户输入的账号和密码封装到shiro框架提供的token对象中
        UsernamePasswordToken token = new UsernamePasswordToken(userName, DigestUtils.sha256Hex(password));
        Subject currentUser = SecurityUtils.getSubject();
        try{
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
        }catch(IncorrectCredentialsException ice){
            throw new GlobalHandleException(ResultCode.USER_PASS_ERROR);
        }catch (UnknownAccountException uae){
            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
        }catch (AuthenticationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
        }catch (AuthorizationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
        }
        return currentUser.getPrincipal();
    }


    @RequestMapping("check")
    @ResponseBody
    public boolean check(Integer id){

        return false;
    }


}
